package experimentForth;

import java.util.ArrayList;
import java.util.HashMap;

class UserFileDirectory {
    //用户文件目录[UFD]
    private HashMap<String, File> ufd;

    // 运行文件目录[AFD]
    private ArrayList<File> afd;

    // 构造函数，初始化用户文件目录
    public UserFileDirectory() {
        this.ufd = new HashMap<>();
        this.afd = new ArrayList<>();
    }

    // 创建文件，设置保护措施
    public void create(String filename, String protectionCode) {
        if (ufd.size() < 10) {
            File file = new File(filename, protectionCode);
            ufd.put(filename, file);
        } else {
            System.out.println("Reached the limit of files a user can create.");
        }
    }

    // 删除文件
    public void delete(String filename) {
        File file = ufd.get(filename);
        if (file != null) {
            ufd.remove(filename);
            afd.remove(file);
        } else {
            System.out.println("File does not exist.");
        }
    }
    // 打开文件
    public void open(String filename) {
        File file = ufd.get(filename);
        if (file != null) {
            afd.add(file);
        } else {
            System.out.println("File does not exist.");
        }
    }

    // 关闭文件
    public void close(String filename) {
        File file = ufd.get(filename);
        if (file != null) {
            afd.remove(file);
        } else {
            System.out.println("File is not open.");
        }
    }

    // 读取文件
    public void read(String filename) {
        File file = ufd.get(filename);
        if (file != null && afd.contains(file)) {
            System.out.println(file.getContent());
        } else {
            System.out.println("File is not open.");
        }
    }

    // 写入文件
    public void write(String filename, String content) {
        File file = ufd.get(filename);
        if (file != null && afd.contains(file)) {
            file.setContent(new StringBuilder(content));
        } else {
            System.out.println("File is not open.");
        }
    }
}